package events

import (
	"context"
	"encoding/json"
	"github.com/IBM/sarama"
)

type Producer interface {
	ProducePaymentEvent(ctx context.Context, evt PaymentEvent) error
}
type PaymentEventKafkaProducer struct {
	producer sarama.SyncProducer
}

func NewPaymentEventKafkaProducer(pc sarama.SyncProducer) Producer {
	return &PaymentEventKafkaProducer{producer: pc}
}

// ProducePaymentEvent 有复杂的重试逻辑，就用装饰器
func (k *PaymentEventKafkaProducer) ProducePaymentEvent(ctx context.Context, evt PaymentEvent) error {
	data, err := json.Marshal(evt)
	if err != nil {
		return err
	}
	_, _, err = k.producer.SendMessage(&sarama.ProducerMessage{
		Topic: evt.Topic(),
		Value: sarama.ByteEncoder(data),
	})
	return err
}
